// require('dotenv').config();
// const express = require('express');
// const bodyParser = require('body-parser');
// const axios = require('axios'); // 替换OpenAI官方库为axios

// const app = express();
// app.use(bodyParser.json());

// // 静态文件托管（前端页面）
// app.use(express.static('public'));

// // SiliconCloud API调用函数
// async function callSiliconCloudAPI(messages) {
//   try {
//     const response = await axios.post(
//       'https://api.siliconflow.cn/v1/chat/completions', // 替换为实际API地址
//       {
//         model: "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", // 模型名称根据平台调整
//         messages: messages,
//         temperature: 0.7,
//       },
//       {
//         headers: {
//           'Authorization': `Bearer ${process.env.SILICON_CLOUD_API_KEY}`,
//           'Content-Type': 'application/json',
//         },
//       }
//     );
//     return response.data.choices[0].message.content;
//   } catch (error) {
//     console.error('SiliconCloud API Error:', error.response?.data || error.message);
//     throw new Error("AI服务请求失败");
//   }
// }

// // 聊天接口
// app.post('/api/chat', async (req, res) => {
//   try {
//     const { messages } = req.body;
//     const reply = await callSiliconCloudAPI(messages);
//     res.json({ reply });
//   } catch (error) {
//     console.error(error);
//     res.status(500).json({ error: error.message });
//   }
// });

// // 启动服务器
// const PORT = process.env.PORT || 3000;
// app.listen(PORT, () => {
//   console.log(`Server running on http://localhost:${PORT}`);
// });


require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const session = require('express-session'); // 添加session支持
const MemoryStore = require('memorystore')(session); // 简单的内存存储

const app = express();
app.use(bodyParser.json());

// 会话配置
app.use(session({
  secret: process.env.SESSION_SECRET || 'your-secret-key',
  resave: false,
  saveUninitialized: true,
  store: new MemoryStore({
    checkPeriod: 86400000 // 清理过期会话的间隔(ms)
  }),
  cookie: { maxAge: 24 * 60 * 60 * 1000 } // 24小时
}));

// 静态文件托管
app.use(express.static('public'));

// 初始化用户会话中的对话历史
app.use((req, res, next) => {
  if (!req.session.conversation) {
    req.session.conversation = [
      { role: "system", content: "你是一个有帮助的AI助手。" }
    ];
  }
  next();
});

// SiliconCloud API调用函数
async function callSiliconCloudAPI(messages) {
  try {
    const response = await axios.post(
      'https://api.siliconflow.cn/v1/chat/completions',
      {
        model: "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B",
        messages: messages,
        temperature: 0.7,
      },
      {
        headers: {
          'Authorization': `Bearer ${process.env.SILICON_CLOUD_API_KEY}`,
          'Content-Type': 'application/json',
        },
      }
    );
    return response.data.choices[0].message.content;
  } catch (error) {
    console.error('SiliconCloud API Error:', error.response?.data || error.message);
    throw new Error("AI服务请求失败");
  }
}

// 聊天接口
app.post('/api/chat', async (req, res) => {
  try {
    const { message } = req.body; // 现在只接收单条消息
    
    // 添加用户消息到会话历史
    req.session.conversation.push({ role: "user", content: message });
    
    // 调用API时发送整个对话历史
    const reply = await callSiliconCloudAPI(req.session.conversation);
    
    // 添加AI回复到会话历史
    req.session.conversation.push({ role: "assistant", content: reply });
    
    res.json({ reply });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: error.message });
  }
});

// 清空对话历史接口
app.post('/api/clear', (req, res) => {
  req.session.conversation = [
    { role: "system", content: "你是一个有帮助的AI助手。" }
  ];
  res.json({ success: true })
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});